package com.cy.pj.common.aspect;

import com.cy.pj.common.cache.SimpleCacheKey;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Cx
 * @stage secondStageOfWeb
 * @creat 2020-11-12 14:09
 */
@Aspect /* 声明是一个切面对象 */
@Component /* 交给spring管理 */
public class SysCacheAspect {

    private Map<Object, Object> cache = new ConcurrentHashMap<>();
    /* map底层为散列表 ConcurrentHashMap线程安全 */

    //@Pointcut("execution(* com.cy.pj..*.findGoods(..))")
    @Pointcut("@annotation(com.cy.pj.common.annotation.RequiredCache)")
    public void doCache() {
    }

    //@Pointcut("execution(* com.cy.pj..*.deleteById(..))")
    @Pointcut("@annotation(com.cy.pj.common.annotation.ClearCache)")
    public void doClearCache() {
    }

    @Around("doCache()")
    public Object doCacheAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        System.out.println(Arrays.toString(args));
        SimpleCacheKey key = new SimpleCacheKey(args);
        /* 1.优先从缓存取数据 */
        Object result = cache.get(key); /* 暂时设置为固定值 */
        if (result != null) return result;
        /* 2.查询数据库 */
        result = joinPoint.proceed();
        /* 3.将数据存储到缓存对象 */
        cache.put(key, result);
        return result;
    }

    @AfterReturning("doClearCache()") /* 在目标方法成功结束后执行此方法 */
    public void doAfterReturning() {
        cache.clear();
    }
//    @Around("doClearCache()")
//    public Object doClearAround(ProceedingJoinPoint joinPoint) throws Throwable {
//        Object obj = joinPoint.proceed();
//        cache.clear();
//        return obj;
//    }

}
